#!/usr/local/bin/php
<?php
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');
define('DM_OAII_OA_DB_CLUSTER_ID', 21);
define('DM_OAII_OAPRE_DB_CLUSTER_ID', 23);

require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_ERR);
$dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
$oaWebDb = OpDbModel::getInstance($dbConfig, $logger);
$appModel = new OaAppModel(OaAppModel::APP_CONFIG_ENV_PRODUCTION, $logger);

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OA_DB_CLUSTER_ID);
$dbOaIIOa = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOa) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OAPRE_DB_CLUSTER_ID);
$dbOaIIOaPre = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOaPre) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

$sql = "SELECT t1.*, app_area.name AS area_name, app_area.area_code, app_group.name AS group_name, 
	app_group.group_code, app_server.ip_id, app_login_server.environment, app_login_server.app_id FROM 
	app_login_server_valid AS t1 LEFT JOIN app_area ON t1.valid_to_area=app_area.id,
	app_login_server_valid AS t2 LEFT JOIN app_group ON t2.valid_to_group=app_group.id,
	app_login_server_valid AS t3 LEFT JOIN app_server ON t3.valid_to_server=app_server.id,
	app_login_server_valid AS t4 LEFT JOIN app_login_server ON t4.login_server_id=app_login_server.id 
	WHERE t1.id=t2.id AND t1.id=t3.id AND t1.id=t4.id ORDER BY id";
$rows = $oaWebDb->query($sql);
foreach ($rows as $row) {
    $id = (int) $row['id'];
    $groupId = (int) $row['app_id'];
    $areaCode = is_null($row['area_code']) ? -1 : $row['area_code'];
    $groupCode = is_null($row['group_code']) ? -1 : $row['group_code'];
    $ipId = is_null($row['ip_id']) ? -1 : $row['ip_id'];
    if ($row['login_id'] > 0) {
        $logger->info("login id already set: id-$id, app-$groupId, area_code-$areaCode, group_code-$groupCode, ip_id-$ipId");
        continue;
    }
    $sql = "SELECT LOGINID FROM TBLOGINSERVER WHERE SERVICEID=:app_id AND AREAID=:area_code 
    	AND GROUPID=:group_code AND IPID=:ip_id";
    if ($row['environment'] == OaAppModel::APP_CONFIG_ENV_TEST) {
        $st = oci_parse($dbOaIIOaPre, $sql);
    } else if ($row['environment'] == OaAppModel::APP_CONFIG_ENV_PRODUCTION) {
        $st = oci_parse($dbOaIIOa, $sql);
    }
    oci_bind_by_name($st, ':app_id', $groupId);
    oci_bind_by_name($st, ':area_code', $areaCode);
    oci_bind_by_name($st, ':group_code', $groupCode);
    oci_bind_by_name($st, ':ip_id', $ipId);
    if (!oci_execute($st)) {
        $e = oci_error($st);
        $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
        break;
    }
    $row = oci_fetch_assoc($st);
    if ($row) {
        $loginId = (int) $row['LOGINID'];
        $sql = "UPDATE app_login_server_valid SET login_id=$loginId WHERE id=$id";
        if (!$oaWebDb->exec($sql)) {
            $logger->err("repair failed: id-$id, app-$groupId, area_code-$areaCode, group_code-$groupCode, ip_id-$ipId");
        } else {
            $logger->info("repair succeed: id-$id, app-$groupId, area_code-$areaCode, group_code-$groupCode, ip_id-$ipId");
        }
    } else {
        if (!OaSyncInfoLogic::syncLoginServerValidToInfo($id, 'add')) {
            $logger->err("sync login server valid info failed: id-$id, app-$groupId, area_code-$areaCode, group_code-$groupCode, ip_id-$ipId");
        } else {
            $logger->info("sync login server valid info succeed: id-$id, app-$groupId, area_code-$areaCode, group_code-$groupCode, ip_id-$ipId");
        }
    }
}
